package main

import (
	"fmt"
	"log"

	"github.com/streadway/amqp"
)

func main() {
	go client()
	go server()

	var a string
	fmt.Scanln(&a)
}

func failOnError(err error, message string) {
	if err != nil {
		log.Fatalf("%s: %s", err, message)
		panic(fmt.Sprintf("%s: %s", err, message))
	}
}

func getQueue() (*amqp.Connection, *amqp.Channel, *amqp.Queue) {
	connection, err := amqp.Dial("amqp://guest@localhost:5672")
	failOnError(err, "Failed to connect to MQ")
	channel, err := connection.Channel()
	failOnError(err, "Failed to open a channel")
	queue, err := channel.QueueDeclare("hello2", false, false, false, false, nil)
	failOnError(err, "Failed to declare a queue")
	return connection, channel, &queue
}

func server() {
	connection, channel, queue := getQueue()
	defer connection.Close()
	defer channel.Close()

	message := amqp.Publishing{
		ContentType: "application/json",
		Body: []byte(`{"message": "Hello, the World over Heaven!"}`),
	}

	for {
		channel.Publish("", queue.Name, false, false, message)
	}
}

func client() {
	connection, channel, queue := getQueue()
	defer connection.Close()
	defer channel.Close()

	mesages, err := channel.Consume(queue.Name, "", true, false, false, false, nil)
	failOnError(err, "Failed to register a consumer")
	for message := range mesages {
		log.Printf("Received message: %s\n", message.Body)
	}
}
